import datetime
import random
from django.http import Http404
from django.shortcuts import render
from django.http import JsonResponse
from apps.popular_img.utils import PopularUtils
from core.tools.wx_login_verify import wx_login
from core.tools.wx_session import get_wx_session
from apps.popular_img.models import PopularImg, SalesManImg, PopularCash
from finance_c2c.local_settings import Config
from apps.sales_man.models import ChannelPopular
from apps.popular_img.models import SalesManPopular


@wx_login()
def popular_index(request):
    wx_obj = get_wx_session(request)
    try:
        wx_obj.salesman
    except Exception as e:
        print(e)
        raise Http404("对不起，没有权限使用")
    return render(request, "c2c/popular_index.html")


# @wx_login()
# def popular_list(request):
#     wx_obj = get_wx_session(request)
#     salesman = wx_obj.salesman
#     if salesman.qr_code:
#         img_info = PopularImg.objects.filter(status=True)
#         salesman_img_list = []
#         for i in img_info:
#             d = dict()
#             salesman_img = i.salesmanimg_set.filter(salesman=salesman)
#             if salesman_img.exists():
#                 salesman_img_obj = salesman_img.first()
#                 url = salesman_img_obj.sales_img
#                 d["img"] = Config.no_protocol + url
#                 d["name"] = i.name
#             else:
#                 # 生成
#                 save_path = PopularUtils.create(salesman, i)
#                 save_path = "/%s%s" % (Config.media_path, save_path.split(Config.media_path)[1])
#                 save_path = save_path.replace("\\", "/")
#                 # 保存
#                 SalesManImg.objects.create(
#                     salesman=salesman,
#                     sales_img=save_path,
#                     popular_img=i,
#                 )
#                 d["img"] = Config.no_protocol + save_path
#                 d["name"] = i.name
#             salesman_img_list.append(d)
#         cash_info = PopularCash.objects.first()
#         cash_info.update_cash()
#         cash_info.refresh_from_db()
#         cash = '%.2f' % (cash_info.cash / 100)
#         content = {"status": "ok", "salesman_img_list": salesman_img_list, "cash": cash}
#     else:
#         content = {"status": "error", "msg": "请先上传微信二维码"}
#     return JsonResponse(content)


@wx_login()
def popular_list(request):
    wx_obj = get_wx_session(request)
    salesman = wx_obj.salesman
    qr_code_path, status = PopularUtils.check_qrcode(salesman)
    img_info = PopularImg.objects.filter(status=True)
    salesman_img_list = []
    for i in img_info:
        d = dict()
        salesman_img = i.salesmanimg_set.filter(salesman=salesman)
        if salesman_img.exists() and status:
            salesman_img_obj = salesman_img.first()
            url = salesman_img_obj.sales_img
            d["img"] = Config.no_protocol + url
            d["name"] = i.name
        else:
            save_path = PopularUtils.create(salesman, i, qr_code_path)
            save_path = "/%s%s" % (Config.media_path, save_path.split(Config.media_path)[1])
            save_path = save_path.replace("\\", "/")
            save_path += "?%s%s" % (datetime.datetime.now().strftime("%Y%m%d%H%M%S"), random.randint(1, 100))
            # 保存
            salesman_info = SalesManImg.objects.filter(salesman=salesman, popular_img=i)
            if salesman_info.exists():
                salesman_info.update(
                    sales_img=save_path
                )
            else:
                SalesManImg.objects.create(
                    salesman=salesman,
                    sales_img=save_path,
                    popular_img=i,
                )
            d["img"] = Config.no_protocol + save_path
            d["name"] = i.name
        salesman_img_list.append(d)
    cash_info = PopularCash.objects.first()
    cash_info.update_cash()
    cash_info.refresh_from_db()
    cash = '%.2f' % (cash_info.cash / 100)
    content = {"status": "ok", "salesman_img_list": salesman_img_list, "cash": cash}
    return JsonResponse(content)


@wx_login()
def popular_one(request):
    wx_obj = get_wx_session(request)
    salesman = wx_obj.salesman
    from apps.sales_man.tools import compare_level
    if compare_level(salesman):
        pass
    else:
        content = {"status": "error", "msg": "show dialog"}
        return JsonResponse(content)
    qr_code_path, status = PopularUtils.check_qrcode(salesman)
    img_info = PopularImg.objects.filter(status=True).order_by("-id").first()
    salesman_img = img_info.salesmanimg_set.filter(salesman=salesman)
    if salesman_img.exists() and status:
        url = salesman_img.first().sales_img
        url = Config.no_protocol + url
        # url = "//127.0.0.1:8002" + url
        # url = "https://c2c.kalaibao.com" + url
    else:
        save_path = PopularUtils.create(salesman, img_info, qr_code_path)
        save_path = "/%s%s" % (Config.media_path, save_path.split(Config.media_path)[1])
        save_path = save_path.replace("\\", "/")
        save_path += "?%s%s" % (datetime.datetime.now().strftime("%Y%m%d%H%M%S"), random.randint(1, 100))
        SalesManImg.objects.create(
            salesman=salesman,
            sales_img=save_path,
            popular_img=img_info,
        )
        url = Config.no_protocol + save_path
        # url = "//127.0.0.1:8002" + save_path
        # url = "https://c2c.kalaibao.com" + save_path
    content = {"url": url}
    return JsonResponse(content)


@wx_login()
def channel_popular(request):
    """
    我的》 渠道推广图
    :param request:
    :return:
    """
    wx_obj = get_wx_session(request)
    salesman = wx_obj.salesman
    from apps.sales_man.tools import compare_level
    if compare_level(salesman):
        pass
    else:
        content = {"status": "error", "msg": "show dialog"}
        return JsonResponse(content)
    qr_code_path, status = PopularUtils.check_qrcode(salesman)  # 查看二维码是否有效
    sales_popular_query = salesman.salesmanpopular_set.filter(popular_img__channel=salesman.channel,
                                                              popular_img__status=True).order_by('-id')
    if sales_popular_query.exists():
        url = sales_popular_query.first().sales_img
        url = Config.no_protocol + url
    else:
        channel_popular_obj = ChannelPopular.objects.filter(status=True, channel=salesman.channel).order_by(
            '-id').first()  # 获取到channel_popular 对象
        # 如果不存在就需要生成了
        file_name = '%s-%s.jpg' % (salesman.pk, channel_popular_obj.id)
        img_path = channel_popular_obj.img.url  # 上传的推广图
        code_size = eval(channel_popular_obj.code_size)
        position = eval(channel_popular_obj.code_position)
        save_path = PopularUtils.create_channel_popular(img_path, file_name, qr_code_path, catalog="popular/cp/",
                                                        qrcode_box=code_size, position=position)
        save_path = "/%s%s" % (Config.media_path, save_path.split(Config.media_path)[1])
        save_path = save_path.replace("\\", "/")
        save_path += "?%s%s" % (datetime.datetime.now().strftime("%Y%m%d%H%M%S"), random.randint(1, 100))
        SalesManPopular.objects.create(
            popular_img=channel_popular_obj,
            salesman=salesman,
            sales_img=save_path,
        )
        url = Config.no_protocol + save_path
    content = {"url": url}
    return JsonResponse(content)
